package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.LagouCodeService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;

@Service(version = "2.7.3")
public class LagouCodeServiceImpl implements LagouCodeService {

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Value("${timeout.codeTimeout}")
    private int codeTimeout;

    @Override
    public void create(String email, String code) {
        long createTime = System.currentTimeMillis();
        long expireTime = createTime + codeTimeout * 1000;

        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreatetime(new Date(createTime));
        lagouAuthCode.setExpiretime(new Date(expireTime));
        lagouAuthCodeDao.save(lagouAuthCode);
    }

    @Override
    public int validate(String email, String code) {
        LagouAuthCode latest = lagouAuthCodeDao.findFirstByEmailOrderByIdDesc(email);
        //0-正确，1-错误，2-超时
        if (latest == null) {
            return 1;
        }
        if (!latest.getCode().equalsIgnoreCase(code)) {
            return 1;
        }

        long expireTime = latest.getExpiretime().getTime();
        if (expireTime <= System.currentTimeMillis()) {
            return 2;
        }
        return 0;
    }
}
